package com.zsc.shixun.utils;

import com.zsc.shixun.config.UserSecurity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * <p>
 *
 * </p>
 *
 * @author ZWYZY
 * @since 2020/6/15
 */
@Service
public class LoginMessageUtils {
    /**
     * 根据登录后获取登录信息
     *
     * @return
     */
    public UserSecurity getMessage() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        UserSecurity principal = (UserSecurity) authentication.getPrincipal();
        return principal;
    }

    /**判断是否登录
     * @return
     */
    public Object isLogin(){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if(authentication.getPrincipal() instanceof String)
        {
            return -1;
        }else{
            UserSecurity principal = (UserSecurity) authentication.getPrincipal();

            return principal.getLoginUser().getId();
        }
    }

    /**
     * 动态更新登录信息
     *
     * @param userDetails
     */
    public void setMessage(UserDetails userDetails) {
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities()));
    }


}
